package controller

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/mjcode-max/TurboGin/internal/service"
	"github.com/mjcode-max/TurboGin/internal/utils"
)

type RankController struct {
	rankService service.IRankService
}

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

// 原始数据结构
type Item struct {
	Clearance int    `json:"clearance"`
	ID        int    `json:"id"`
	Name      string `json:"name"`
	Rank      string `json:"rank"`
}

func (c *RankController) PublicProvinceRank(ctx *gin.Context) Response {
	result, err := c.rankService.GetProvinceRankList(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return Response{
			Code: 1,
			Data: nil,
			Msg:  "failed",
		}
	}
	// 将对象数组转换为字符串并去除 \ 和多余空格
	jsonData, err := json.Marshal(result)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to marshal data"})
		return Response{
			Code: 1,
			Data: nil,
			Msg:  "failed",
		}
	}

	_data := utils.ModificationData(string(jsonData))

	resp := Response{
		Code: 0,
		Data: _data,
		Msg:  "success",
	}

	return resp
}

func (c *RankController) GetSkinsRank(ctx *gin.Context) {
	resp := c.PublicProvinceRank(ctx)
	if resp.Code != 0 {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": resp.Msg})
		return
	}

	if dataList, ok := resp.Data.([]interface{}); ok {
		for i := range dataList {
			if item, ok := dataList[i].(map[string]interface{}); ok {
				if item["code"] != nil {
					result, err := c.rankService.GetProvinceSkinsList(ctx, item["code"].(string))
					if err != nil {
						ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
						return
					}

					jsonData, err := json.Marshal(result)
					if err != nil {
						ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to marshal data"})
					}

					_data := utils.ModificationData(string(jsonData))
					if skinsdataList, ok := _data.([]interface{}); ok {
						for i := range skinsdataList {
							if item, ok := skinsdataList[i].(map[string]interface{}); ok {
								path := fmt.Sprintf("%v", item["path"]) // 使用 %v 格式化任何类型为字符串
								picture := fmt.Sprintf("%v", item["picture"])
								url := "/" + path + "/" + picture
								item["url"] = utils.AddGenerateSignedUrl(url)
							}
						}
					}
					item["skins"] = _data
				}
			}
		}
	}

	_resp := Response{
		Code: 0,
		Data: resp.Data,
		Msg:  "success",
	}

	ctx.JSON(http.StatusOK, _resp)
}

func (c *RankController) GetRank(ctx *gin.Context) {
	resp := c.PublicProvinceRank(ctx)
	if resp.Code != 0 {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": resp.Msg})
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

func NewRankController() *RankController {
	r := &service.RankService{}
	return &RankController{rankService: r}
}
